package com.dy.dynotinstalled

import android.content.Intent
import android.os.Bundle
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import com.dy.dynotinstalled.room.NotDoorInformation
import com.dy.dynotinstalled.room.NotDoorInformationViewModel
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.util.regex.Pattern


class MainActivity : AppCompatActivity() {


    lateinit var mLoadingDialog: ProgressLoading
    private var doorInformationViewModel: NotDoorInformationViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        mLoadingDialog = ProgressLoading.create(this)

        doorInformationViewModel =
            ViewModelProviders.of(this).get(NotDoorInformationViewModel::class.java)
    }


    private fun initView() {

        button_scan.setOnClickListener {
            IntentIntegrator(this)
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                //.setPrompt("请对准二维码")// 设置提示语
                .setCameraId(0)// 选择摄像头,可使用前置或者后置
                .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                .setCaptureActivity(QrCodeActivity::class.java)//自定义扫码界面
                .initiateScan()// 初始化扫码
        }

        button4.setOnClickListener {

            startActivity<DetailsActivity>()
        }


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)


        //扫码结果
        val intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (intentResult != null) {
            if (intentResult.contents == null) {


                toast("扫码失败")

            } else {
                val result = intentResult.contents//返回值


//              val  result = "462EA0BB-8309-4E18-9D0A-666666666666"
                mLoadingDialog.showLoading()
                object : Thread() {
                    override fun run() {
                        val okHttpClient = OkHttpClient()


                        val notDoorPlatesReq = NotDoorPlatesReq(
                            "foshan",
                            "qrcode_classification",
                            "${getZhEnNum(result)}",
                            "无法安装"
                        )

                        val gson = Gson()
                        //使用Gson将对象转换为json字符串
                        val json = gson.toJson(notDoorPlatesReq)

                        //MediaType  设置Content-Type 标头中包含的媒体类型值
                        val requestBody = FormBody.create(
                            MediaType.parse("application/json; charset=utf-8"),
                            json
                        )

                        val request = Request.Builder()
                            .url("http://dytech.tpddns.cn:23333/doorplates")//请求的url
                            .put(requestBody)
                            .build()

                        //创建/Call
                        val call = okHttpClient.newCall(request)

                        call.enqueue(object : Callback {
                            override fun onFailure(call: Call, e: IOException) {
                                roomDatabaseFail(getZhEnNum(result))
                                mLoadingDialog.hideLoading()
                            }

                            @Throws(IOException::class)
                            override fun onResponse(call: Call, response: Response) {
                                mLoadingDialog.hideLoading()
                                val string = response.body()?.string()
                                if (string != null) {
                                    try {
                                        val jsonObject = JSONObject(string)
                                        val status = jsonObject.getBoolean("status")
                                        Looper.prepare()
                                        if (status) {

                                            toast(jsonObject.getString("msg"))


                                            roomDatabase(getZhEnNum(result))

                                            IntentIntegrator(this@MainActivity)
                                                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                                                //.setPrompt("请对准二维码")// 设置提示语
                                                .setCameraId(0)// 选择摄像头,可使用前置或者后置
                                                .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                                                .setCaptureActivity(QrCodeActivity::class.java)//自定义扫码界面
                                                .initiateScan()// 初始化扫码

                                        } else {
                                            toast(jsonObject.getString("msg"))

                                            roomDatabaseFail(getZhEnNum(result))
                                        }

                                        Looper.loop()

                                    } catch (e: JSONException) {
                                        e.printStackTrace()
                                    }
                                }
                            }
                        })

                    }
                }.start()


            }
        }
    }


    private fun roomDatabase(global_id: String) {
        var doorInformation = NotDoorInformation("", "", "", "", "")

        doorInformation =
            NotDoorInformation(
                "foshan",
                "qrcode_classification",
                global_id,
                "无法安装",
                "成功"
            )


        doorInformationViewModel?.insertDoorInformation(doorInformation)

    }



    private fun roomDatabaseFail(global_id: String) {
        var doorInformation = NotDoorInformation("", "", "", "", "")

        doorInformation =
            NotDoorInformation(
                "foshan",
                "qrcode_classification",
                global_id,
                "无法安装",
                "失败"
            )


        doorInformationViewModel?.insertDoorInformation(doorInformation)

    }


    /**
     * @description java 获取中英文 + 数字
     * @author Li Xuyang
     * @time 2019年9月20日 晚上22:08:09
     * @param str
     * @return
     */
    fun getZhEnNum(str: String): String {
        //   String regZhEnNum = "[\\u4e00-\\u9fa5[a-zA-Z][0-9]]";
        //{36}表示前面的字符需要36个
        val regZhEnNum = "[[a-zA-Z][0-9][-]]{36}"//中括号里填入需要的即可得到需要的
        return matchResult(Pattern.compile(regZhEnNum), str)
    }

    /**
     * @description java 匹配正则
     * @author Li Xuyang
     * @time 2019年9月20日 晚上22:18:09
     * @param p
     * @param str
     * @return
     */
    fun matchResult(p: Pattern, str: String): String {
        val sb = StringBuilder()
        val m = p.matcher(str)
        while (m.find())
            for (i in 0..m.groupCount()) {
                sb.append(m.group())
            }
        return sb.toString()
    }


}
